import time
import os
import sys
import concurrent.futures
import warnings
import requests
import threading

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.api.services.translators import TranslateClient
from app.api.schemas import Lang, FragmentTransResultDict, TextTransResult
from app.utils import DocxUtils

# 禁用 SSL 证书验证警告
warnings.filterwarnings(
    "ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning
)


# translator = TranslateFactory.get_translator("edge")
translator = TranslateClient.get_translator("baidu")


def translate_content(trans_entity: TextTransResult):
    thread_name = threading.current_thread().name
    print(
        f"线程名称: {thread_name} 正在处理内容: {trans_entity.src[:30]}..."
    )  # 打印线程名称和内容的前 30 个字符
    return translator.translate_entity(trans_entity, use_proxy=True)


def read_content_from_file(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        return file.readlines()


def write_content_to_file(file_path, trans_dict: FragmentTransResultDict):
    with open(file_path, "w", encoding="utf-8") as file:
        for entity in trans_dict.values():
            file.write(f"{entity}\n")


if __name__ == "__main__":
    input_file_path = r"D:\原文.docx"
    output_dir = r"D:\临时文件夹\translate_doc\out"
    os.makedirs(output_dir, exist_ok=True)

    doc_util = DocxUtils(input_file_path, Lang.EN, Lang.ZH)

    trans_dict = FragmentTransResultDict()
    doc_util.extranct_text(trans_dict)

    start = time.time()
    # 使用 ThreadPoolExecutor 进行多线程翻译
    with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
        # 提交所有翻译任务
        futures = [
            executor.submit(translate_content, trans_entity)
            for trans_entity in trans_dict.values()
        ]

        for future in concurrent.futures.as_completed(futures):
            # future.result()
            continue

    # 将翻译结果写入docx文件
    doc_util.replace_text(trans_dict)
    doc_util.save(output_dir + "\\output.docx")
    write_content_to_file(output_dir + "\\" + "output.txt", trans_dict)

    print("------------------------------------\n")
    print("耗时：{:.2f} 秒".format(time.time() - start))
